
//  CYLClassifyMenuViewController.m
//  CollectionViewClassifyMenu
//
//  Created by chenyilong on 15/3/17.
//  Copyright (c) 2015年 chenyilong. All rights reserved.
//


#import "CYLClassifyMenuViewController.h"
#import "ClassifyCustomCelModel.h"
#import "SearchSndViewController.h"

#define jsonHeadName @"Type"
#define jsonSection @"Menu"
#define jsonCell @"Food_Name"

@interface CYLClassifyMenuViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
{
    CGAdapter _myAd;
}
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *datasourceArray;
@property (nonatomic, retain) UIScrollView *scrollView;
@property (nonatomic, retain) UITextField *field;
@property (nonatomic, assign) NSInteger actionSelect;
@property (nonatomic, assign) NSInteger actionSelect1;
@property (nonatomic, assign) NSInteger actionSelect2;
@property (nonatomic, assign) NSInteger actionSelect3;
@property (nonatomic, assign) NSInteger actionSelect4;
@property (nonatomic, assign) NSInteger firstTag;
@property (nonatomic, assign) NSInteger firstTag1;
@property (nonatomic, assign) NSInteger firstTag2;
@property (nonatomic, assign) NSInteger firstTag3;
@property (nonatomic, assign) NSInteger firstTag4;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *array1;
@property (nonatomic, retain) NSMutableArray *array2;
@property (nonatomic, retain) NSMutableArray *array3;
@property (nonatomic, retain) NSMutableArray *array4;
@property (nonatomic, retain) NSMutableArray *array5;
@property (nonatomic, retain) NSMutableArray *showArray;
@property (nonatomic, retain) NSMutableDictionary *menuDic;
@property (nonatomic, assign) NSInteger moreButtonCount;

@end

@implementation CYLClassifyMenuViewController

- (void)dealloc
{
    [_array release];
    [_array1 release];
    [_array2 release];
    [_array3 release];
    [_array4 release];
    [_array5 release];
    [_showArray release];
    [_menuDic release];
    [_collectionView release];
    [_datasourceArray release];
    [_scrollView release];
    [_field release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.actionSelect = 0;
        self.actionSelect1 = 0;
        self.actionSelect2 = 0;
        self.actionSelect3 = 0;
        self.actionSelect4 = 0;
        self.firstTag = 0;
        self.firstTag1 = 0;
        self.firstTag2 = 0;
        self.firstTag3 = 0;
        self.firstTag4 = 0;
        self.array = [NSMutableArray array];
        self.array1 = [NSMutableArray array];
        self.array2 = [NSMutableArray array];
        self.array3 = [NSMutableArray array];
        self.array4 = [NSMutableArray array];
        self.array5 = [NSMutableArray array];
        self.showArray = [NSMutableArray array];
        self.menuDic = [NSMutableDictionary dictionary];
        self.moreButtonCount = 0;
        
        _myAd = [AdapterModel getCGAdapter];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self creatData];
    [self creatCustomBar];
    [self creatBackground];
    [self creatScrollView];
    [self creatCollectionView];
    [self creatSearch];
}

- (void)creatBackground
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64)];
    [imageView setImage:[UIImage imageNamed:@"searchPhoto1.png"]];
    [self.view addSubview:imageView];
    [imageView release];
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    _scrollView.scrollEnabled = YES;
    [self updateHeight];
}

#pragma mark - 创建搜索栏
- (void)creatSearch
{
    self.field = [[UITextField alloc] initWithFrame:CGRectMake(10, 74, 250 * _myAd.sWidth, 30)];
    [_field setBorderStyle:UITextBorderStyleRoundedRect];
    [_field setPlaceholder:@"请输入关键字"];
    [_field setTextColor:[UIColor blackColor]];
    
    UIButton *searcjButton = [[UIButton alloc] initWithFrame:CGRectMake(270 * _myAd.sWidth, 74, 60 * _myAd.sWidth, 30)];
    searcjButton.layer.cornerRadius = 10.0;
    [searcjButton setBackgroundColor:[UIColor colorWithRed:187/255.0 green:188/255.0 blue:192/255.0 alpha:1.0]];
    searcjButton.layer.borderWidth = 1.0f;
    [searcjButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searcjButton.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
    [searcjButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [searcjButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [searcjButton addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_field];
    [self.view addSubview:searcjButton];
    
    [_field release];
    [searcjButton release];
}

#pragma mark - 搜索摁钮方法
- (void)searchButtonAction:(id)sender
{
    [_field resignFirstResponder];
    [_array5 removeAllObjects];
    
    [_array5 addObject:_field.text];
    NSString *str = [NSString stringWithFormat:@"%@", [_array5 firstObject]];
    if ([_array firstObject] == nil) {
        [_array addObject:@""];
    }
    if ([_array1 firstObject] == nil) {
        [_array1 addObject:@""];
    }
    if ([_array2 firstObject] == nil) {
        [_array2 addObject:@""];
    }
    if ([_array3 firstObject] == nil) {
        [_array3 addObject:@""];
    }
    if ([_array4 firstObject] == nil) {
        [_array4 addObject:@""];
    }
    NSString *arr = [NSString stringWithFormat:@"%@", [_array firstObject]];
    NSString *arr1 = [NSString stringWithFormat:@"%@", [_array1 firstObject]];
    NSString *arr2 = [NSString stringWithFormat:@"%@", [_array2 firstObject]];
    NSString *arr3 = [NSString stringWithFormat:@"%@", [_array3 firstObject]];
    NSString *arr4 = [NSString stringWithFormat:@"%@", [_array4 firstObject]];
    
    NSLog(@"a0 = %@, a1=%@, a2=%@,a3=%@, a4=%@,str = %@", arr, arr1, arr2, arr3, arr4, str);
    if ([arr isEqualToString:@""] && [arr1 isEqualToString:@""] && [arr2 isEqualToString:@""] && [arr3 isEqualToString:@""] && [arr4 isEqualToString:@""] && [str isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"亲，请选择类别再搜索哦～" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    } else {
        
        NSLog(@"a0 = %@, a1=%@, a2=%@,a3=%@, a4=%@,str = %@", arr, arr1, arr2, arr3, arr4, str);
        NSString *dress = [NSString stringWithFormat:@"http://121.41.88.194:80/HandheldKitchen/api/vegetable/tblvegetable!getVegetableInfo.do?name=%@&child_catalog_name=%@&taste=%@&fitting_crowd=%@&cooking_method=%@&effect=%@&page=", str, arr, arr3, arr4, arr2, arr1];
        NSMutableArray *urlArray = [NSMutableArray array];
        [urlArray addObject:dress];
        [urlArray addObject:@"1"];
        [urlArray addObject:@"&pageRecord=10&is_traditional=0&user_id=&phonetype=0"];
        NSLog(@"urlArray = %@", urlArray);
        SearchSndViewController *snd = [[SearchSndViewController alloc] init];
        snd.dressArray = urlArray;
        [self.navigationController pushViewController:snd animated:YES];
        [snd release];
    }
    _field.text = @"";
}

#pragma mark - 放弃第一响应者
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [_field resignFirstResponder];
}

#pragma mark - 创建scrollView
- (void)creatScrollView
{
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 114, self.view.frame.size.width, self.view.frame.size.height - 114)];
    _scrollView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scrollView];
    [_scrollView release];
}

#pragma mark - 创建自定义navigationBar
- (void)creatCustomBar
{
    UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    bar.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0];
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 40, 40)];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bar];
    [bar addSubview:button];
    
    [button release];
    [bar release];
}

#pragma mark - 返回按钮方法
- (void)backButtonAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 解析json数据
- (void)creatData
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    _datasourceArray = [NSMutableArray arrayWithArray:jsonArray];
}



#pragma mark - 创建CollectionView
- (void)creatCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.itemSize = CGSizeMake(80 * _myAd.sWidth, 30 * _myAd.sHeight);
    flow.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    flow.minimumInteritemSpacing = 5;
    flow.minimumLineSpacing = 5;
    flow.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 30);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, self.view.frame.size.height - 124) collectionViewLayout:flow];
    [flow release];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [_collectionView registerClass:[ClassifyCustomCelModel class] forCellWithReuseIdentifier:@"menu"];
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    _collectionView.scrollEnabled = NO;
    [_scrollView addSubview:_collectionView];
}

#pragma mark - 刷新高度
- (void)updateHeight
{
    _collectionView.frame = CGRectMake(self.collectionView.frame.origin.x, self.collectionView.frame.origin.y, self.collectionView.frame.size.width, self.collectionView.contentSize.height);
    
    _scrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width,  self.collectionView.contentSize.height + 20);
}

#pragma mark - Section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    [_datasourceArray retain];
    return [self.datasourceArray count];
}

#pragma mark - Item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *menuArray = [NSArray arrayWithArray:[_datasourceArray[section] objectForKey:jsonSection]];
    
    return menuArray.count;

}

#pragma mark - cell赋值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ClassifyCustomCelModel *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"menu" forIndexPath:indexPath];
    cell.button.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
    NSMutableArray *menu = [NSMutableArray arrayWithArray:[_datasourceArray[indexPath.section] objectForKey:jsonSection]];
    NSString *text = [menu[indexPath.row] objectForKey:jsonCell];
    // 设Tag值
    cell.button.tag = (indexPath.section + 1) * 100 + indexPath.item;
    
    
//    [cell.button setTitle:text forState:UIControlStateNormal];
    [cell.label setText:text];
    [cell.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [cell.button addTarget:self action:@selector(buttonAtion:)
          forControlEvents:UIControlEventTouchUpInside];
    cell.button.section = indexPath.section;
    cell.button.row = indexPath.row;
    cell.button.layer.cornerRadius = 10.0;
    
    return cell;
    
}

#pragma mark - button方法
- (void)buttonAtion:(ClassifyCustomButton *)button
{
    [_field resignFirstResponder];
    //section0
    if (button.section == 0) {
        
        if (_actionSelect == 0) {
            button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
            _firstTag = button.tag;
            _actionSelect ++;
            NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
            NSString *text = [menu[button.row] objectForKey:jsonCell];
            NSLog(@"%@", text);
            
            [_array removeAllObjects];
            [_array addObject:text];
            NSLog(@"_array = %@", _array);
        } else {
            if (button.tag != _firstTag) {
                UIButton *firstButton = (UIButton *)[self.view viewWithTag:_firstTag];
                firstButton.backgroundColor = [UIColor clearColor];
                button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
                _firstTag = button.tag;
                NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
                NSString *text = [menu[button.row] objectForKey:jsonCell];
                NSLog(@"%@", text);
                
                [_array removeAllObjects];
                [_array addObject:text];
                NSLog(@"_array = %@", _array);
            } else {
                button.backgroundColor = [UIColor clearColor];
                _actionSelect --;
                _firstTag = 0;
                [_array removeAllObjects];
                NSLog(@"_array = %@", _array);
            }
        }
    }
    //section1
    else if (button.section == 1) {
        if (_actionSelect1 == 0) {
            button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
            _firstTag1 = button.tag;
            _actionSelect1 ++;
            NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
            NSString *text = [menu[button.row] objectForKey:jsonCell];
            NSLog(@"%@", text);
            
            [_array1 removeAllObjects];
            [_array1 addObject:text];
            NSLog(@"_array1 = %@", _array1);
        } else {
            if (button.tag != _firstTag1) {
                UIButton *firstButton = (UIButton *)[self.view viewWithTag:_firstTag1];
                firstButton.backgroundColor = [UIColor clearColor];
                button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
                _firstTag1 = button.tag;
                NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
                NSString *text = [menu[button.row] objectForKey:jsonCell];
                NSLog(@"%@", text);
                
                [_array1 removeAllObjects];
                [_array1 addObject:text];
                NSLog(@"_array1 = %@", _array1);
            } else {
                button.backgroundColor = [UIColor clearColor];
                _actionSelect1 --;
                _firstTag1 = 0;
                [_array1 removeAllObjects];
                NSLog(@"_array1 = %@", _array1);
            }
        }
    }
    //section2
    else if (button.section == 2) {
        if (_actionSelect2 == 0) {
            button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
            _firstTag2 = button.tag;
            _actionSelect2 ++;
            NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
            NSString *text = [menu[button.row] objectForKey:jsonCell];
            NSLog(@"%@", text);
            
            [_array2 removeAllObjects];
            [_array2 addObject:text];
            NSLog(@"_array2 = %@", _array2);
            
        } else {
            if (button.tag != _firstTag2) {
                UIButton *firstButton = (UIButton *)[self.view viewWithTag:_firstTag2];
                firstButton.backgroundColor = [UIColor clearColor];
                button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
                _firstTag2 = button.tag;
                NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
                NSString *text = [menu[button.row] objectForKey:jsonCell];
                NSLog(@"%@", text);
                
                [_array2 removeAllObjects];
                [_array2 addObject:text];
                NSLog(@"_array2 = %@", _array2);
            } else {
                button.backgroundColor = [UIColor clearColor];
                _actionSelect2 --;
                _firstTag2 = 0;
                [_array2 removeAllObjects];
                NSLog(@"_array2 = %@", _array2);
            }
        }
    }
    //section3
    else if (button.section == 3) {
        if (_actionSelect3 == 0) {
            button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
            _firstTag3 = button.tag;
            _actionSelect3 ++;
            NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
            NSString *text = [menu[button.row] objectForKey:jsonCell];
            NSLog(@"%@", text);
            
            [_array3 removeAllObjects];
            [_array3 addObject:text];
            NSLog(@"_array3 = %@", _array3);
        } else {
            if (button.tag != _firstTag3) {
                UIButton *firstButton = (UIButton *)[self.view viewWithTag:_firstTag3];
                firstButton.backgroundColor = [UIColor clearColor];
                button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
                _firstTag3 = button.tag;
                NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
                NSString *text = [menu[button.row] objectForKey:jsonCell];
                NSLog(@"%@", text);
                
                [_array3 removeAllObjects];
                [_array3 addObject:text];
                NSLog(@"_array = %@", _array3);
                
            } else {
                button.backgroundColor = [UIColor clearColor];
                _actionSelect3 --;
                _firstTag3 = 0;
                [_array3 removeAllObjects];
                NSLog(@"_array3 = %@", _array3);
            }
        }
        
    }
    //section4
    else if (button.section == 4) {
        if (_actionSelect4 == 0) {
            button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
            _firstTag4 = button.tag;
            _actionSelect4 ++;
            NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
            NSString *text = [menu[button.row] objectForKey:jsonCell];
            NSLog(@"%@", text);
            
            [_array4 removeAllObjects];
            [_array4 addObject:text];
            NSLog(@"_array4 = %@", _array4);
        } else {
            if (button.tag != _firstTag4) {
                UIButton *firstButton = (UIButton *)[self.view viewWithTag:_firstTag4];
                firstButton.backgroundColor = [UIColor clearColor];
                button.backgroundColor = [UIColor colorWithRed:133/255.0 green:213/255.0 blue:247/255.0 alpha:1.0];
                _firstTag4 = button.tag;
                NSMutableArray *menu = [NSMutableArray arrayWithArray:[self.datasourceArray[button.section] objectForKey:jsonSection]];
                NSString *text = [menu[button.row] objectForKey:jsonCell];
                NSLog(@"%@", text);
                
                [_array4 removeAllObjects];
                [_array4 addObject:text];
                NSLog(@"_array4 = %@", _array4);
            } else {
                button.backgroundColor = [UIColor clearColor];
                _actionSelect4 --;
                _firstTag4 = 0;
                [_array4 removeAllObjects];
                NSLog(@"_array = %@", _array4);
            }
        }
    }
}

#pragma mark - CollectionView顶部设计
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(150 * _myAd.sWidth, 0, 75, 30)];
        [button setBackgroundColor:[UIColor clearColor]];
        button.layer.cornerRadius = 10.0;
        UILabel *classifyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, button.bounds.size.width, button.bounds.size.height)];
        
        classifyLabel.layer.cornerRadius = 10.0;
        NSString *sectionTitle = [_datasourceArray[indexPath.section] objectForKey:jsonHeadName];
        
        [classifyLabel setText:sectionTitle];
        classifyLabel.textAlignment = NSTextAlignmentCenter;
        [classifyLabel setTextColor:[UIColor blackColor]];
        
        
            
        
        
        [button addSubview:classifyLabel];
        [header addSubview:button];
        [button release];
        return (UICollectionReusableView *)header;
    }
    return nil;
    
}

@end
